<template>
  <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" @close="closeDialog">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="父级菜单" prop="parentId">
        <el-tree-select v-model="formData.parentId" placeholder="选择上级菜单" :data="props.menuSelectTree" filterable
          check-strictly :render-after-expand="false" />
      </el-form-item>
      <el-form-item label="菜单名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入菜单名称" />
      </el-form-item>
      <el-form-item label="菜单类型" prop="type">
        <el-radio-group v-model="formData.type">
          <el-radio v-for="type in props.menuType" :value="type.value"> {{ type.label }} </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="formData.type == props.menuType[3].value" label="外链地址" prop="path">
        <el-input v-model="formData.routePath" placeholder="请输入外链完整路径" />
      </el-form-item>

      <el-form-item v-show="formData.type == props.menuType[1].value" prop="routeName">
        <template #label>
          <div class="flex-y-center">
            路由名称
            <el-tooltip placement="bottom" effect="light">
              <template #content>
                如果需要开启缓存，需保证页面 defineOptions 中的 name 与此处一致，建议使用驼峰。
              </template>
              <el-icon class="ml-1 cursor-pointer">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </div>
        </template>
        <el-input v-model="formData.routeName" placeholder="User" />
      </el-form-item>

      <el-form-item v-show="formData.type == props.menuType[0].value || formData.type == props.menuType[1].value"
        prop="routePath">
        <template #label>
          <div class="flex-y-center">
            路由路径
            <el-tooltip placement="bottom" effect="light">
              <template #content>
                定义应用中不同页面对应的 URL 路径，目录需以 / 开头，菜单项不用。例如：系统管理目录
                /system，系统管理下的用户管理菜单 user。
              </template>
              <el-icon class="ml-1 cursor-pointer">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </div>
        </template>
        <el-input v-show="formData.type == props.menuType[0].value" v-model="formData.routePath"
          placeholder="/system" />
        <el-input v-show="formData.type !== props.menuType[0].value" v-model="formData.routePath" placeholder="user" />
      </el-form-item>

      <el-form-item v-show="formData.type == props.menuType[1].value" prop="component">
        <template #label>
          <div class="flex-y-center">
            组件路径
            <el-tooltip placement="bottom" effect="light">
              <template #content>
                组件页面完整路径，相对于 src/views/，如 system/user/index，缺省后缀 .vue
              </template>
              <el-icon class="ml-1 cursor-pointer">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </div>
        </template>

        <el-input v-model="formData.component" placeholder="system/user/index" style="width: 95%">
          <template v-show="formData.type == props.menuType[1].value" #prepend>src/views/</template>
          <template v-show="formData.type == props.menuType[1].value" #append>.vue</template>
        </el-input>
      </el-form-item>

      <el-form-item v-show="formData.type == props.menuType[1].value">
        <template #label>
          <div class="flex-y-center">
            路由参数
            <el-tooltip placement="bottom" effect="light">
              <template #content>
                组件页面使用 `useRoute().query.参数名` 获取路由参数值。
              </template>
              <el-icon class="ml-1 cursor-pointer">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </div>
        </template>

        <div v-show="!formData.params || formData.params.length === 0">
          <el-button type="success" plain @click="formData.params = [{ key: '', value: '' }]">
            添加路由参数
          </el-button>
        </div>

        <div v-show="formData.params || formData.params.length !== 0">
          <div v-for="(item, index) in formData.params" :key="index">
            <el-input v-model="item.key" placeholder="参数名" style="width: 100px" />

            <span class="mx-1">=</span>

            <el-input v-model="item.value" placeholder="参数值" style="width: 100px" />

            <el-icon v-if="formData.params.indexOf(item) === formData.params.length - 1"
              class="ml-2 cursor-pointer color-[var(--el-color-success)]" style="vertical-align: -0.15em"
              @click="formData.params.push({ key: '', value: '' })">
              <CirclePlusFilled />
            </el-icon>
            <el-icon class="ml-2 cursor-pointer color-[var(--el-color-danger)]" style="vertical-align: -0.15em"
              @click="formData.params.splice(formData.params.indexOf(item), 1)">
              <DeleteFilled />
            </el-icon>
          </div>
        </div>
      </el-form-item>

      <el-form-item v-show="formData.type !== props.menuType[2].value" prop="visible" label="显示状态">
        <el-radio-group v-model="formData.visible">
          <el-radio :value="1">显示</el-radio>
          <el-radio :value="0">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-show="formData.type === props.menuType[0].value || formData.type === props.menuType[2].value">
        <template #label>
          <div class="flex-y-center">
            始终显示
            <el-tooltip placement="bottom" effect="light">
              <template #content>
                选择“是”，即使目录或菜单下只有一个子节点，也会显示父节点。
                <br />
                选择“否”，如果目录或菜单下只有一个子节点，则只显示该子节点，隐藏父节点。
                <br />
                如果是叶子节点，请选择“否”。
              </template>
              <el-icon class="ml-1 cursor-pointer">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </div>
        </template>

        <el-radio-group v-model="formData.alwaysShow">
          <el-radio :value="1">是</el-radio>
          <el-radio :value="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-show="formData.type === props.menuType[1].value" label="缓存页面">
        <el-radio-group v-model="formData.keepAlive">
          <el-radio :value="1">开启</el-radio>
          <el-radio :value="0">关闭</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" style="width: 100px" controls-position="right" :min="0" />
      </el-form-item>

      <!-- 权限标识 -->
      <el-form-item v-show="formData.type == props.menuType[2].value" label="权限标识" prop="perm">
        <el-input v-model="formData.perm" placeholder="sys:user:add" />
      </el-form-item>

      <el-form-item v-show="formData.type !== props.menuType[2].value" label="图标" prop="icon">
        <!-- 图标选择器 -->
        <icon-select v-model="formData.icon" />
      </el-form-item>

      <el-form-item v-show="formData.type == props.menuType[0].value" label="跳转路由">
        <el-input v-model="formData.redirect" placeholder="跳转路由" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit" :loading="loading">确 定</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { cloneDeep, omit, pick } from 'lodash-es';
import MenuAPI from '@/api/system/menu.api';
import { nextTick, reactive } from 'vue';

const props = defineProps({
  menuSelectTree: {
    required: true,
    type: Array,
    default: [],
  },
  menuType: {
    required: true,
    type: Array,
    default: [],
  },
});
let loading = ref(false);
const emit = defineEmits(['subemit']);

const dialog = reactive({
  visible: false,
  title: '新增'
});
const formRef = ref(null);
const fields = ['id', 'parentId', 'name', 'type', 'routePath', 'routeName', 'component', 'params', 'visible', 'alwaysShow', 'keepAlive', 'sort', 'perm', 'icon', 'redirect'];
let formData = reactive({
  id: undefined,
  parentId: 0, //父级菜单
  name: '', //菜单名称
  type: 2, //菜单类型
  routePath: '', //路由路径
  routeName: '', //路由名称
  component: '', //组件路径
  params: '', //路由参数
  visible: 1, //显示状态
  alwaysShow: 1, //始终显示
  keepAlive: 1, //缓存页面
  sort: 0, //缓存页面
  perm: '', //权限标识
  icon: '', //图标
  redirect: '', //重定向
});

const rules = reactive({
  parentId: [{ required: true, message: "请选择父级菜单", trigger: "blur" }],
  name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择菜单类型", trigger: "blur" }],
  routeName: [{ required: true, message: "请输入路由名称", trigger: "blur" }],
  routePath: [{ required: true, message: "请输入路由路径", trigger: "blur" }],
  component: [{ required: true, message: "请输入组件路径", trigger: "blur" }],
  visible: [{ required: true, message: "请选择显示状态", trigger: "change" }],
});

//提交
function handleSubmit() {
  loading.value = true;
  formRef.value.validate((valid) => {
    if (valid) {
      const params = cloneDeep(formData);
      if (params.id === params.parentId) {
        loading.value = false;
        return ElMessage.warning('不能选择自己作为父级菜单');
      }
      // const params = omit(params_v, ['role_ids']);  //删除对象中某一项
      if (params.id) {
        MenuAPI.update(params).then(res => {
          ElMessage.success("修改成功");
          closeDialog();
          emit('subemit');
        }).finally(() => {
          loading.value = false;
        });
      } else {
        MenuAPI.create(params).then(res => {
          ElMessage.success("新增成功");
          closeDialog();
          emit('subemit');
        }).finally(() => {
          loading.value = false;
        });
      }
    }
  });
};

function showForm(ty, data) {
  if (ty === 'edit') {
    dialog.title = '编辑';
    const record_v = cloneDeep(data);
    const record = pick(record_v, fields); //保留fields中的字段
    nextTick(() => {
      Object.assign(formData, record);
    })
  }
  if (ty === 'add') {
    dialog.title = '新增';
    console.log('formData', formData)
    formData.parentId = data
  }
  dialog.visible = true;

};

//取消
function closeDialog() {
  formRef.value.resetFields();
  dialog.visible = false;
};

//重置表单
function reset(elForm) {
  elForm.resetFields();
};

defineExpose({ showForm });
</script>
<style lang="scss" scoped></style>
